import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';
import { warnId } from '../../common/warnId';

export default {
	tags: ['api', 'warnId'],
	description: '告警ID列表',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		query: Joi.object({
			taskType: Joi.string().description('任务类型'),
		}).unknown(),
	},

	response: {
		schema: Joi.array()
			.items(
				Joi.object({
					id: Joi.string().description('异常ID'),
					category: Joi.string().description('类别'),
					taskType: Joi.string().description('任务类型'),
					label: Joi.string().description('名称'),
				})
			)
			.label('Response'),
	},

	async handler(request) {
		const {
			query: { taskType },
			server: {
				methods: { getVulPluginList },
			},
		} = request;

		let vulWarnIds;
		try {
			vulWarnIds = await getVulPluginList();
		} catch (error) {
			error.messageSuffix('warnId');
			request.log.error({ error }, error.detail);
			throw error;
		}

		return [].concat(vulWarnIds).reduce((arr, x) => {
			if (taskType && x.taskType !== taskType) {
				return arr;
			}

			arr.push({
				...x,
				id: warnId({ id: x.id, taskType: x.taskType }),
			});

			return arr;
		}, []);
	},
};
